package com.yjzx.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.logging.Logger;

/**
 * @author yjzx
 * @date 2023/10/25
 * @description
 */

public class SystemUtil {
    
    private static final Logger logger = Logger.getLogger(SystemUtil.class.getName());
    public static final boolean IS_WINDOWS = isWindows();
    public static final String TEMP = "temp";
    public static final String TEMP_DIR = "temp";
    public static final String LINUX_SCRIPT = "temp.sh";
    public static final String WINDOWS_SCRIPT = "temp.bat";

    public static final String LINUX_COMMAND = "/bin/sh";
    public static final String WINDOWS_COMMAND = "cmd.exe";

    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");

    }

    /**
     * 查询文件编码
     * @param file 文件路径
     * @return
     */
    public static String getFileCharsetName(File file) {
        //GB2312 ANSI
        String charsetName ="GBK";
        try (FileInputStream inputStream = new FileInputStream(file)){
            byte[] head = new byte[3];
            inputStream.read(head);
            if (head[0]==-1 && head[1]==-2){
                charsetName = "UTF-16";
            }else if (head[0]==-2 && head[1]==-1){
                // UCS2-Big-Endian UCS-Little-Endian
                charsetName = "Unicode";
            }else if (head[0]==-27 && head[1]==-101&& head[2]==-98){
                //无BOM
                charsetName = "UTF-8";
            }else if (head[0]==-17 && head[1]==-69&& head[2]==-65) {
                // BOM
                charsetName = "UTF-8";
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return charsetName;
    }
    /**
     * 执行cmd命令并输出
     *
     * @param finalFile 缓存根路径
     * @param command 命令（linux没有测试）
     */
    public static void extracted(File finalFile, String command) {
        BufferedReader br = null;
        try {
            File file = new File(finalFile + File.separator +TEMP_DIR);
            if (!file.exists()) {
                file.mkdirs();
            }
            //新建一个用来存储结果的缓存文件
            File tmpFile = new File(file + File.separator + TEMP);
            File script;
            String exec;
            if (SystemUtil.IS_WINDOWS) {
                script = new File(file + File.separator + WINDOWS_SCRIPT);
                exec = WINDOWS_COMMAND;
            }else {
                script = new File(file + File.separator + LINUX_SCRIPT);
                exec = LINUX_COMMAND;
            }
            FileUtil.addFile(false, tmpFile,script);

            try (FileOutputStream outputStream = new FileOutputStream(script)) {
                String path = "cd " + finalFile + "\r\n" + command;
                outputStream.write(path.getBytes(StandardCharsets.UTF_8));
            }

            logger.info("------------------------------执行命令-----------------------------------");
            ProcessBuilder pb = new ProcessBuilder().command(exec, "/c", script.getPath()).inheritIO();
            //允许如异常打印（红色字体）
            pb.redirectErrorStream(true);
            pb.redirectOutput(tmpFile);
            //等待语句执行完成，否则可能会读不到结果。
            pb.start().waitFor();

            String encode = getFileCharsetName(tmpFile);
            InputStream in = Files.newInputStream(tmpFile.toPath());
            br = new BufferedReader(new InputStreamReader(in, encode));
            String line;
            while ((line = br.readLine()) != null) {
                logger.info(line);
            }
            br.close();
            br = null;
            FileUtil.delFolder(file);
            logger.info("执行完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
